package com.paradogs.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.paradogs.common._cfg.Cfg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: yumi
 * @date: 2024/3/28  14:57
 * @Description: JWT 令牌生成工具
 */
@Component
public class JwtUtils
{
    public static final String UID_KEY = "uid";
    public static final String IS_GM_KEY = "isGM";

    /** jwt 盐值 */
    public static String SECRET;
    @Value("${server.jwt-salt:Miaomiao777@}")
    public void setSECRET(String secret) {
        JwtUtils.SECRET = secret;
    }

    /** 60 秒过期 */
    public static final long EXPIRED_TIME = 60 * 1000;

    /** 生成令牌 TOTO JSONObject */
    public static String buildToken(Long uid, Boolean isGM) {
        return JWT.create()
                .withClaim(UID_KEY, uid) // 在JWT中加入uid作为自定义声明
                .withClaim(IS_GM_KEY, isGM)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRED_TIME))
                .sign(Algorithm.HMAC512(SECRET));
    }

    /** 验证 JWT */
    public static boolean verifyToken(String token) {
        if (token == null) {return false;}
        try {
            Algorithm algorithm = Algorithm.HMAC512(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception){
            return false;
        }
    }

    /** 根据令牌获得 uid */
    public static Long getUserId(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC512(SECRET))
                .build()
                .verify(token);
        return jwt.getClaim(UID_KEY).asLong();
    }

    public static Boolean isGM(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC512(SECRET))
                .build()
                .verify(token);
        return jwt.getClaim(IS_GM_KEY).asBoolean();
    }

}
